package com.jy.modules.cims.common.open.api.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;
import com.jy.modules.cims.common.open.api.exception.JieYueApiException;

public class JieYueApiUtils {
	public static Map<String, String> obj2Map(Object obj, String... exclude) {
		Map<String, String> param = new HashMap<String, String>();

		Set<String> excludeSet = new HashSet<String>();
		if (exclude != null) {
			for (String str : exclude) {
				excludeSet.add(str);
			}
		}
		try {
			Class<?> c = obj.getClass();
			Field[] fs = c.getDeclaredFields();
			for (Field f : fs) {
				String fieldName = f.getName();
				if ((!Modifier.isStatic(f.getModifiers()))
						&& (!excludeSet.contains(fieldName))) {
					Object o = c.getMethod(
							"get" + fieldName.substring(0, 1).toUpperCase()
									+ fieldName.substring(1), new Class[0])
							.invoke(obj, new Object[0]);
					if (o != null) {
						param.put(fieldName, o.toString());
					}
				}
			}
			return param;
		} catch (Exception e) {
			throw new JieYueApiException("Object转换为Map失败", e);
		}
	}

	public static <T> T parse(String str, Class<T> c) {
		T result = null;
		if (str == null) {
			return result;
		}
		if ((str.startsWith("{")) && (str.endsWith("}")) && (c != String.class)) {
			result = parseObject(str, c);
		} else if ((str.startsWith("[")) && (str.endsWith("]"))
				&& (c.isArray())) {
			result = parseObject(str, c);
		} else if ((c == String.class) || (c == BigDecimal.class)
				|| (c == Integer.class) || (c == Long.class)
				|| (c == Double.class) || (c == Float.class)) {
			try {
				result = c.getConstructor(new Class[] { String.class })
						.newInstance(new Object[] { str });
			} catch (Exception e) {
				throw new JieYueApiException("字符串转化对象失败" + str + ", " + c);
			}
		} else {
			throw new JieYueApiException("不支持的参数方式" + str + ", " + c);
		}
		return result;
	}

	public static String toString(Object obj) {
		String result = null;
		if (obj == null) {
			return result;
		}
		Class<?> c = obj.getClass();
		if (c == String.class) {
			result = obj.toString();
		} else if ((c == BigDecimal.class) || (c == Integer.class)
				|| (c == Long.class) || (c == Double.class)
				|| (c == Float.class)) {
			result = obj.toString();
		} else {
			result = toJSONString(obj);
		}
		return result;
	}

	public static <T> T parseObject(String json, Class<T> c) {
		return JSONObject.parseObject(json, c);
	}

	public static <T> List<T> parseList(String json, Class<T> c) {
		return JSONObject.parseArray(json, c);
	}

	public static String toJSONString(Object obj) {
		return JSONObject.toJSONString(obj);
	}
}
